package com.ml.mall.service.partner.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ml.mall.bean.base.ApiRestResult;
import com.ml.mall.bean.req.partner.*;
import com.ml.mall.bean.res.partner.PartnerInterestIndustryRes;
import com.ml.mall.bean.res.partner.PartnerQueryInfoRes;
import com.ml.mall.consts.CommonConsts;
import com.ml.mall.entity.company.SysCompany;
import com.ml.mall.entity.company.SysCompanyInterestIndustry;
import com.ml.mall.entity.sys.SysUser;
import com.ml.mall.enums.CommonEnum;
import com.ml.mall.enums.SysSeqNameEnum;
import com.ml.mall.exception.BizException;
import com.ml.mall.mapper.company.SysCompanyInterestIndustryMapper;
import com.ml.mall.mapper.company.SysCompanyMapper;
import com.ml.mall.security.JwtUtil;
import com.ml.mall.service.asyn.AuthMailServiceImplAsyn;
import com.ml.mall.service.common.CommonSeqService;
import com.ml.mall.service.company.SysCompanyInterestIndustryService;
import com.ml.mall.service.partner.SysPartnerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.validation.constraints.NotEmpty;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SysPartnerServiceImpl extends ServiceImpl<SysCompanyMapper, SysCompany> implements SysPartnerService {

    @Autowired
    private CommonSeqService commonSeqService;
    @Autowired
    private SysCompanyMapper sysCompanyMapper;

    @Autowired
    private SysCompanyInterestIndustryService sysCompanyInterestIndustryService;
    @Autowired
    private SysCompanyInterestIndustryMapper sysCompanyInterestIndustryMapper;

    @Lazy
    @Autowired
    private AuthMailServiceImplAsyn authMailServiceImplAsyn;

    /**
     * @description    :合作商邀请商户
     * @author         :zxm
     * @date           :2021/5/20
    **/
    @Override
    public ApiRestResult partnerInviterMerchant(PartnerDto dto) {
        SysCompany sysCompany = sysCompanyMapper.selectByCompanyId(JwtUtil.getCurrentUser().getCompanyId());
        dto.setInviteCode(sysCompany.getInviteCode());
        dto.setCompanyName(sysCompany.getCompanyName());
        authMailServiceImplAsyn.inviterPartenerAsyn(dto);


//        MailMessage msg = new MailMessage();
//        msg.setReceiverEmail(dto.getPartnerEmail());
//        msg.setSubject("邮件主题");
//        msg.setContent("邮件正文");
    //    MailMessage msg = mailService.sendForPartnerInvitationLink(dto.getPartnerEmail());

//        mailService.sendMail(msg);  //真正发送邮件

   //     String message = JSON.toJSONString(msg);
     //   RedisClient.lpush(MailConsts.REDIS_MAIL_MESSAGE,message);
        return ApiRestResult.ok();
    }

    @Override
    public ApiRestResult createPartner(PartnerNewDto dto) {
        // 判断邀请码是否已经存在
        int inviteCodeNum = sysCompanyMapper.selectCountByInviteCode(dto.getInviteCode());
        if(inviteCodeNum > 0){
            throw new BizException(CommonEnum.ALREADY_EXISTS_SAME_INVITCODE);
        }

        SysCompany sysCompany = new SysCompany();
        BeanUtils.copyProperties(dto,sysCompany);
        Long companyId = commonSeqService.nextSysOrderSeq(SysSeqNameEnum.SEQ_PARTNER_ID.getCode());
        sysCompany.setCompanyId(companyId);
        sysCompany.setCompanyType(2); //类型是合作商
        sysCompany.setState(CommonConsts.FIXED_NUM_ZERO);
        int isAdd = sysCompanyMapper.insert(sysCompany);
        if(isAdd < 1){
            throw new BizException(CommonEnum.INSERT_ERROR);
        }
        //批量创建感兴趣的产业
        List<SysCompanyInterestIndustry> listCompanyIndustry = new ArrayList<>();
        for(Long industryId : dto.getIndustryArr()){
            SysCompanyInterestIndustry sysCompanyInterestIndustry = new SysCompanyInterestIndustry();
            sysCompanyInterestIndustry.setCompanyId(companyId);
            sysCompanyInterestIndustry.setIndustryId(industryId);
            listCompanyIndustry.add(sysCompanyInterestIndustry);
        }
        sysCompanyInterestIndustryService.saveBatch(listCompanyIndustry);

        //发送邮件
        authMailServiceImplAsyn.createPartnerMailAsyn(dto);

        return ApiRestResult.ok();
    }

    @Override
    public PartnerQueryInfoRes queryOnePartner(PartnerQueryOneDto dto) {
        SysCompany sysCompany = sysCompanyMapper.selectById(dto.getId());
        if(null == sysCompany){
            throw new BizException(CommonEnum.COMPANY_IS_NOT_EXIST);
        }
        PartnerQueryInfoRes partnerQueryInfoRes = new PartnerQueryInfoRes();
        BeanUtils.copyProperties(sysCompany,partnerQueryInfoRes);

        //查询感兴趣的产业
        List<SysCompanyInterestIndustry> sysCompanyInterestIndustries = sysCompanyInterestIndustryMapper.selectByCompanyId(sysCompany.getCompanyId());
        PartnerInterestIndustryRes interestIndustryRes = new PartnerInterestIndustryRes();
        sysCompanyInterestIndustries.forEach(industry -> {
            if(CommonConsts.INDUSTRY_OTHER.equals(industry.getIndustryId())){
                interestIndustryRes.setOtherName(industry.getIndustryOther());
            }
            interestIndustryRes.getInterestedIdArr().add(industry.getIndustryId());
        });
        interestIndustryRes.setCompanyId(partnerQueryInfoRes.getCompanyId());
        interestIndustryRes.setId(partnerQueryInfoRes.getId());

        partnerQueryInfoRes.setInterestIndustryObj(interestIndustryRes);
        return partnerQueryInfoRes;
    }

    @Override
    public IPage<SysCompany> queryPagePartner(PartnerQueryDto dto) {
        Page<SysCompany> page = new Page<>(dto.getPageIndex(),dto.getPageNum());
        QueryWrapper<SysCompany> wrapper = new QueryWrapper<>();
        wrapper.like(StringUtils.hasText(dto.getCompanyName()),"company_name",dto.getCompanyName());
        wrapper.eq("company_type",CommonConsts.ROLE_TYPE_PARTNER);
        wrapper.eq(dto.getStatus() != null, "state", dto.getStatus());
        wrapper.orderByDesc(StringUtils.hasText(dto.getOrderBy()),dto.getOrderBy());
        page = sysCompanyMapper.selectPage(page,wrapper);
        return page;
    }

    @Override
    public int updateCompanyRegister(PartnerDelCompanyDto dto) {

        //管理员调用该接口；无需校验 当前用户
        SysUser currentUser = JwtUtil.getCurrentUser();
        if(!CommonConsts.ROLE_TYPE_ADMIN.equals(currentUser.getRoleType())){
            throw new BizException(CommonEnum.NO_ASSOCIATION_BETWEEN_SUPPLIER_AND_PARTNER);
        }
//        SysCompany supplier = sysCompanyMapper.selectById(dto.getId());

//        SysCompany partner = sysCompanyMapper.selectByCompanyId(currentUser.getCompanyId());
//
//        //如果合作商不属于本公司，抛出异常
//        if(null != supplier && supplier.getRegistartionNo() != null){
//            if(!ObjectUtil.equals(supplier.getRegistartionNo(), partner.getInviteCode())){
//                throw new BizException(CommonEnum.NO_ASSOCIATION_BETWEEN_SUPPLIER_AND_PARTNER);
//            }
//        }else{
//            throw new BizException(CommonEnum.NO_ASSOCIATION_BETWEEN_SUPPLIER_AND_PARTNER);
//        }

        //将供应商注册号置空
        return sysCompanyMapper.updateRegister(dto.getId());
    }

    @Override
    public void partnerInviter(PartnerDto dto) {
        authMailServiceImplAsyn.partnerInviterMailAsyn(dto);
    }

    @Override
    public Integer allocationSupplier(AllocationSupplierDto dto) {
        //查询合作商信息
        LambdaQueryWrapper<SysCompany> partnerWrapper = new LambdaQueryWrapper<>();
        partnerWrapper.eq(SysCompany::getCompanyId, dto.getPartnerId());
        SysCompany partnerCompany = sysCompanyMapper.selectOne(partnerWrapper);
        //更新供应商信息
        LambdaUpdateWrapper<SysCompany> supplierWrapper = new LambdaUpdateWrapper<>();
        supplierWrapper.set(SysCompany::getRegistartionNo, partnerCompany.getInviteCode())
                       .eq(SysCompany::getCompanyId, dto.getSupplierId());
        return sysCompanyMapper.update(null, supplierWrapper);
    }

}
